package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.HaoHanYouJieSsqUtil;
import com.block.datapush.service.apipush.utils.MobileMd5IsInListUtils;
import com.block.db.entity.*;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 *  浩瀚有借全授权
 */
@Service
public class HaoHanApiBRateService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    MerchantDataPushInfoMapper  merchantDataPushInfoMapper;
    @Autowired
    MemberSourceInfoMapper memberSourceInfoMapper;



    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String queryUrl = pushApiKeyParam.getCheckUrl();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name_md5", SecureUtil.md5(memberSourceInfo.getRealname()));
        paramMap.put("phone_md5", memberSourceInfo.getMobileMd5());
        paramMap.put("idno_md5", SecureUtil.md5(memberSourceInfo.getIdcard()));
        //paramMap.put("phone_mask", memberSourceInfo.getMobileMask());
        paramMap.put("age",String.valueOf(memberSourceInfo.getAge()));
        if (memberSourceInfo.getSex() == 1){
            paramMap.put("sex", "男");
        }else {
            paramMap.put("sex", "女");
        }
        if (StringUtils.isNotEmpty(memberSourceInfo.getReqIp())){
            paramMap.put("ip", memberSourceInfo.getReqIp());
        }else {
            paramMap.put("ip", "127.0.0.1");
        }
        StringBuilder stringBuilder = new StringBuilder();
        String provinceCity = stringBuilder.append(memberSourceInfo.getProvince()).append("/").append(memberSourceInfo.getCity()).toString();
        paramMap.put("working_city",provinceCity);
        paramMap.put("salary_type","银行代发");
        paramMap.put("loan_amount", HaoHanYouJieSsqUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("loan_period", HaoHanYouJieSsqUtil.getloanTime(memberSourceInfo.getLoanTime()));
        paramMap.put("reserved_funds",HaoHanYouJieSsqUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("social_security",HaoHanYouJieSsqUtil.getshebao(memberSourceInfo.getShebao()));
        paramMap.put("credit_record",HaoHanYouJieSsqUtil.getyuqi(memberSourceInfo.getYuqi()));
        paramMap.put("insurance",HaoHanYouJieSsqUtil.getbaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("real_estate",HaoHanYouJieSsqUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("zhima",HaoHanYouJieSsqUtil.getzhima(memberSourceInfo.getZhima()));
        paramMap.put("car",HaoHanYouJieSsqUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("industry",HaoHanYouJieSsqUtil.getJob(memberSourceInfo.getGongzuo()));
        paramMap.put("loan_lately", "没有申请过贷款");


        log.info("【浩瀚半流程导量】 撞库开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【浩瀚半流程导量】撞库结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer respCode = resultObject.getInteger("code");
        String respMsg = resultObject.getString("msg");

        pushApiResult.setCode(String.valueOf(respCode));
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (respCode != 0) {
            pushApiResult.setPushSuccess(false);
            return pushApiResult;
        }
        String tid = resultObject.getString("tid");
        String url = resultObject.getString("url");
        pushApiResult.setPushSuccess(true);
        pushApiResult.setOutOrderNo(tid);
        extJson.put("url",url);
//        JSONArray list = resultObject.getJSONArray("list");
//        for (int i = 0; i < list.size(); i++) {
//            JSONObject item = list.getJSONObject(i);
//            JSONArray data = item.getJSONArray("data");
//            if(MobileMd5IsInListUtils.isMobileMd5InList(data,memberSourceInfo.getMobileMd5())){
//                pushApiResult.setCode(respCode + "|" + "500");
//                pushApiResult.setMessage(respMsg + "|" + memberSourceInfo.getMobileMd5() + "号码已存在");
//                pushApiResult.setPushSuccess(false);
//                return pushApiResult;
//            }
//        }
        

        extJson.put("code",String.valueOf(respCode));
        extJson.put("message",respMsg);
        //extJson.put("resultInfo",result);
        extJson.put("outOrderNo",tid);
        pushApiResult.setExtJson(extJson);

        //进行分润操作
        String priceType = pushApiKeyParam.getPriceType();
        BigDecimal typeRate = pushApiKeyParam.getTypeRate();
        if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
            BigDecimal price = resultObject.getBigDecimal("price");//下游返回分润后价格
            if (price.compareTo(new BigDecimal(0.00)) == -1){
                pushApiResult.setPushSuccess(false);
                return pushApiResult;
            }
            BigDecimal priceLeft = price.multiply(typeRate);//分润前价格
            pushApiResult.setPrice(price);
            pushApiResult.setPriceRight(priceLeft);
        }

        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        String url = extJson.getString("url");
        String code = extJson.getString("code");
        String message = extJson.getString("message");
        String resultInfo = extJson.getString("resultInfo");
        String outOrderNo = extJson.getString("outOrderNo");
        pushApiResult.setApproveUrl(url);
        pushApiResult.setCode(code);
        pushApiResult.setMessage(message);
        //pushApiResult.setResultInfo(resultInfo);
        pushApiResult.setOutOrderNo(outOrderNo);
        pushApiResult.setPushSuccess(true);
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(true);
        pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
        noticeParamDTO.setQueryResult(paramContent);
        JSONObject jsonObject = JSON.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObject)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }
        String outOrderNo = jsonObject.getString("tid");

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(outOrderNo));
        if (ObjectUtil.isEmpty(entityByOutOrderNoLock) || PushStatusEnum.SUCCESS.getValue().equals(entityByOutOrderNoLock.getStatus())){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
        }
        noticeParamDTO.setOutOrderNo(outOrderNo);
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);
        return noticeParamDTO;

    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        String infoId = extObject.getString("infoId");
        JSONObject parseObject = JSON.parseObject(paramContent);
        String outOrderNo = parseObject.getString("tid");
        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(outOrderNo));
        MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.getEntityByUidLock(entityByOutOrderNoLock.getUid());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("tid",outOrderNo);
        jsonObject.put("name",memberSourceInfo.getRealname());
        jsonObject.put("idno",memberSourceInfo.getIdcard());
        jsonObject.put("phone",memberSourceInfo.getMobile());
        JSONObject returnData = new JSONObject();
        returnData.put("returnData",jsonObject);
        returnData.put("settleFlag",true);
        returnData.put("pushSuccess",true);
        return returnData;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

}
